// 获取存储的 token
export const getToken = () => {
    const token = localStorage.getItem('token');
    // console.log('🔍 getToken 调用:', {
    //     token: token ? `${token.substring(0, 20)}...` : 'null',
    //     localStorage_length: localStorage.length,
    //     all_keys: Object.keys(localStorage),
    //     stack: new Error().stack.split('\n')[1] // 显示调用来源
    // });
    return token;
};

// 存储 token
export const setToken = (token) => {
    if (token) {
        //console.log('💾 正在存储 token:', token.substring(0, 20) + '...');
        localStorage.setItem('token', token);
        //console.log('✅ 存储完成，验证:', localStorage.getItem('token') ? '成功' : '失败');
    } else {
        //console.error('❌ 尝试存储空的 token');
    }
};

// 移除 token - 添加调用栈追踪
export const removeToken = () => {
    //console.log('🗑️ removeToken 被调用!', new Error().stack);
    localStorage.removeItem('token');
    localStorage.removeItem('user');
};

// 获取当前用户信息
export const getCurrentUser = () => {
    try {
        const userStr = localStorage.getItem('user');
        // 检查是否存在且不是 "undefined" 字符串
        if (userStr && userStr !== 'undefined' && userStr !== 'null') {
            return JSON.parse(userStr);
        }
        return null;
    } catch (error) {
        //console.error('Error parsing user data:', error);
        // 清除损坏的数据
        localStorage.removeItem('user');
        return null;
    }
};

// 存储用户信息
export const setCurrentUser = (user) => {
    if (user) {
        localStorage.setItem('user', JSON.stringify(user));
    } else {
        localStorage.removeItem('user');
    }
};

// 验证 JWT token 格式
const isValidJWTFormat = (token) => {
    if (!token || typeof token !== 'string') {
        //console.log('❌ Token 不存在或不是字符串:', typeof token);
        return false;
    }

    // JWT 应该有三个部分，用 . 分隔
    const parts = token.split('.');
    if (parts.length !== 3) {
        //console.log('❌ JWT 部分数量错误:', parts.length);
        return false;
    }

    // 检查每个部分是否是有效的 Base64
    try {
        parts.forEach((part, index) => {
            if (!part) {
                throw new Error(`Part ${index} is empty`);
            }
            // 转换 URL-safe Base64 到标准 Base64
            const base64 = part.replace(/-/g, '+').replace(/_/g, '/');
            // 添加必要的填充
            const padded = base64 + '='.repeat((4 - base64.length % 4) % 4);
            atob(padded);
        });
        //console.log('✅ JWT 格式验证通过');
        return true;
    } catch (error) {
        //console.log('❌ JWT Base64 解码失败:', error.message);
        return false;
    }
};

// 解码 JWT payload
const decodeJWTPayload = (token) => {
    try {
        if (!isValidJWTFormat(token)) {
            return null;
        }

        const parts = token.split('.');
        const payload = parts[1];

        // 转换 URL-safe Base64 到标准 Base64
        const base64 = payload.replace(/-/g, '+').replace(/_/g, '/');
        // 添加必要的填充
        const padded = base64 + '='.repeat((4 - base64.length % 4) % 4);
        const decoded = atob(padded);

        return JSON.parse(decoded);
    } catch (error) {
        //console.error('Error decoding JWT payload:', error);
        return null;
    }
};

// 检查是否已认证
export const isAuthenticated = () => {
    try {
        const token = getToken();

        // 检查 token 是否存在
        if (!token) {
            //console.log('No token found');
            return false;
        }

        // 验证 token 格式
        if (!isValidJWTFormat(token)) {
            //console.error('Invalid JWT format');
            removeToken();
            return false;
        }

        // 解码并检查是否过期
        const payload = decodeJWTPayload(token);
        if (!payload) {
            //console.error('Failed to decode JWT payload');
            removeToken();
            return false;
        }

        // 检查是否有过期时间
        if (payload.exp) {
            const currentTime = Date.now() / 1000;
            if (payload.exp < currentTime) {
                //console.log('Token expired');
                removeToken();
                return false;
            }
        }

        //console.log('Token is valid');
        return true;

    } catch (error) {
        //console.error('Error in isAuthenticated:', error);
        removeToken();
        return false;
    }
};

// 获取 token 中的用户信息
export const getUserFromToken = () => {
    try {
        const token = getToken();
        if (!token || !isValidJWTFormat(token)) {
            return null;
        }

        const payload = decodeJWTPayload(token);
        return payload ? {
            username: payload.sub || payload.username,
            exp: payload.exp,
            iat: payload.iat
        } : null;
    } catch (error) {
        //console.error('Error getting user from token:', error);
        return null;
    }
};

// 调试函数 - 检查当前存储的数据
export const debugAuth = () => {
    const token = getToken();
    const user = getCurrentUser();

    console.log('=== Auth Debug Info ===');
    console.log('Token exists:', !!token);
    console.log('Token (first 50 chars):', token ? token.substring(0, 50) + '...' : 'null');
    console.log('Token format valid:', token ? isValidJWTFormat(token) : false);
    console.log('User data:', user);
    console.log('Is authenticated:', isAuthenticated());

    if (token) {
        const payload = decodeJWTPayload(token);
        console.log('Token payload:', payload);
    }

    console.log('=======================');
};

// 监听 localStorage 变化
if (typeof window !== 'undefined') {
    window.addEventListener('storage', (e) => {
        if (e.key === 'token') {
            console.log('🔄 localStorage token 变化:', {
                oldValue: e.oldValue,
                newValue: e.newValue,
                url: e.url
            });
        }
    });

    // 监听页面卸载
    window.addEventListener('beforeunload', () => {
        console.log('📄 页面即将卸载，当前 token:', localStorage.getItem('token') ? '存在' : '不存在');
    });
}